package com.catfive.jet_work.ui

import android.annotation.SuppressLint
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.calculateTargetValue
import androidx.compose.animation.core.tween
import androidx.compose.animation.rememberSplineBasedDecay
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.draggable
import androidx.compose.foundation.gestures.rememberDraggableState
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.requiredWidth
import androidx.compose.foundation.layout.width
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.compose.rememberNavController

import com.catfive.jet_work.core.design.layout.ScreenContent
import com.catfive.jet_work.core.design.layout.ScreenDrawer
import com.catfive.jet_work.feature.switchpanel.SWITCH_PANEL_ROUTE
import com.catfive.jet_work.viewmodel.NavigationViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch


@SuppressLint("UnrememberedMutableState")
@Composable
fun MyApp() {
    Scaffold(
        modifier = Modifier.fillMaxSize(),
    ) { innerPadding ->

        val drawerWidth = 300.dp
        val endWidth = with(LocalDensity.current) { drawerWidth.toPx() }
        val drawPosition = with(LocalDensity.current) { -drawerWidth.toPx() }

        val isOpen = remember { mutableStateOf(true) }

        var drawerState by remember { mutableStateOf(DrawerState.Closed) }
        val progress = remember { Animatable(0f) }
        val coroutineScope = rememberCoroutineScope()
        val decay = rememberSplineBasedDecay<Float>()

        val draggableState = rememberDraggableState { delta ->
            coroutineScope.launch {
                progress.snapTo((progress.value + delta).coerceIn(0f, endWidth))
            }
        }


        val contentTranslation by derivedStateOf { progress.value }
        val menuTranslation by derivedStateOf { drawPosition + progress.value }
        val overlayAlpha by derivedStateOf {
            (progress.value / endWidth).coerceIn(0f, 0.5f) // 透明度范围0-0.5
        }

        suspend fun closeDrawer(velocity: Float = 0f) {
            progress.animateTo(
                targetValue = 0f,
                initialVelocity = velocity,
                animationSpec = tween(300)
            )
            drawerState = DrawerState.Closed
        }

        suspend fun openDrawer(velocity: Float = 0f) {
            progress.animateTo(
                targetValue = endWidth,
                initialVelocity = velocity,
                animationSpec = tween(300)
            )
            drawerState = DrawerState.Open
        }

        val onDragStopped: suspend CoroutineScope.(Float) -> Unit = { velocity ->
            coroutineScope.launch {
                if (isOpen.value) {
                    val targetX = decay.calculateTargetValue(progress.value, velocity)
                    if (targetX >= endWidth * 0.4) openDrawer() else closeDrawer()
                } else {
                    closeDrawer()
                }
            }
        }


        fun toggleDrawerState() {
            coroutineScope.launch {
                if (drawerState == DrawerState.Open) {
                    closeDrawer()
                } else {
                    openDrawer()
                }
            }
        }

        val navController = rememberNavController()
        val viewModel: NavigationViewModel = hiltViewModel()

        fun onDrawerItemClick(route: String) {
            coroutineScope.launch {
                closeDrawer()
            }
            when (route) {
                SWITCH_PANEL_ROUTE -> {
                    isOpen.value = false
                    navController.navigate(route)
                }

                "confirm_panel" -> {
                    isOpen.value = true
                }

                else -> {
                    isOpen.value = true
                    navController.navigate(route)
                }
            }
        }

        ScreenDrawer(
            modifier = Modifier
                .graphicsLayer(translationX = menuTranslation)
                .then(
                    if (isOpen.value) {
                        Modifier.draggable(
                            state = draggableState,
                            orientation = Orientation.Horizontal,
                            onDragStopped = onDragStopped
                        )
                    } else {
                        Modifier
                    }
                )
                .requiredWidth(drawerWidth)
                .width(drawerWidth)
                .fillMaxHeight()
                .padding(innerPadding),
            onDrawerClicked = ::onDrawerItemClick,
            navModel = viewModel,
        )

        // 遮罩
        ScreenContent(
            modifier = Modifier
                .graphicsLayer(translationX = contentTranslation)
                .then(
                    if (isOpen.value) {
                        Modifier.draggable(
                            state = draggableState,
                            orientation = Orientation.Horizontal,
                            onDragStopped = onDragStopped
                        )
                    } else {
                        Modifier
                    }
                )
                .fillMaxSize(),
            navController = navController,
            navModel = viewModel,
            onDrawerClicked = ::toggleDrawerState,
            onDrawerItemClick = ::onDrawerItemClick
        )

        Box(
            modifier = Modifier
                .graphicsLayer(translationX = contentTranslation, alpha = overlayAlpha)
                .background(Color.Black.copy(alpha = 0.5f))
                .fillMaxSize()
                .then(
                    if (drawerState == DrawerState.Open) {
                        Modifier
                            .clickable {
                                coroutineScope.launch { closeDrawer() }
                            }
                            .draggable(
                                state = draggableState,
                                orientation = Orientation.Horizontal,
                                onDragStopped = onDragStopped
                            )
                    } else {
                        Modifier
                    }
                )
        )
    }
}


@Composable
@Preview
fun PreviewContent() {
    MyApp()
}